<template>
    <el-card style="max-width: 480px;margin: auto;margin-top: 220px;">
        <el-form ref="ruleFormRef" style="max-width: 500px" :model="ruleForm" :rules="rules" label-width="auto">
            <el-form-item label="用户名" prop="userName">
                <el-input v-model="ruleForm.userName" />
            </el-form-item>

            <el-form-item label="密码" prop="userPwd">
                <el-input v-model="ruleForm.userPwd" show-password />
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="submitForm(ruleFormRef)">
                    登录
                </el-button>
                <el-button @click="resetForm(ruleFormRef)">重置</el-button>
            </el-form-item>
        </el-form>
    </el-card>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue'

import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import axios from 'axios'
import { postinfo } from '@/Http/axiosInfo'
import { useRouter } from 'vue-router'
import { useCounterStore } from '@/stores/counter'
import { sw } from 'element-plus/es/locales.mjs'
const store = useCounterStore()
const router = useRouter()
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
    userName: '',
    userPwd: ''
})

const model = reactive({
    validateCode: '',
    validateCode2: '',

    vCode: '',
    vCode2: '',

    result: ''
})

// const getCode = () => {
//     if(model.validateCode)
// }

const setCode = () => {
    let num1 = Math.floor(Math.random() * 10)
    let num2 = Math.ceil(Math.random() * 10)

    let temp = "+-*/"
    let index = Math.floor(Math.random() * 4)
    let sign = temp[index]

    if (sign == "/") {
        num1 = num1 * num2
    }
    let result = 0
    switch (sign) {
        case "+":
            result = num1 + num2
            break;
        case "-":
            result = num1 - num2
            break;
        case "*":
            result = num1 * num2
            break;
        case "/":
            result = num1 / num2
            break;
    }
    model.vCode2 = num1 + num2 + "=?"
    // model.result=
}


const locationOptions = ['Home', 'Company', 'School']

const rules = reactive<FormRules>({
    userName: [
        { required: true, message: '用户名不能为空', trigger: 'blur' },
        // { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
    ],
    userPwd: [
        {
            required: true,
            message: '密码不能为空',
            trigger: 'change',
        },
    ],
})

// const open = () => {
//     if (store.stainfo == false) {
//         ElMessage.error('尚未授权，请重新登录');
//         return;
//     }
// }

onMounted(() => [
    open(),
    setCode()
])

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log('submit!')

            postinfo.post('/Mang/login', ruleForm)
                .then(res => {
                    if (res.data.code == 100) {
                        store.userinfo.userId = res.data.data.userId;
                        store.userinfo.userName = res.data.data.userName;
                        store.userinfo.nickName = res.data.data.nickName;
                        store.userinfo.roleName = res.data.data.roleName;
                        window.localStorage.setItem("token", res.data.token);
                        // 数据提交后端要加入新的Token值
                        axios.defaults.headers.common["Authorization"] =
                            "Bearer " + res.data.token;
                        ElMessage.success(res.data.mes)
                        store.stainfo = true
                        router.push('/AddPermission')
                    }
                    else {
                        ElMessage.error(res.data.mes)
                    }
                })

        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

const options = Array.from({ length: 10000 }).map((_, idx) => ({
    value: `${idx + 1}`,
    label: `${idx + 1}`,
}))
</script>
